package com.coocaa.ops.admin.v1.timedtask.job;


import com.coocaa.ops.admin.async.MyAsyncOpsMgrServiceImpl;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.timedtask.service.impl.TimedTaskServiceImpl;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.model.ResourceBaseModel;
import com.coocaa.ops.common.core.base.util.MyAppContextUtil;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoHistoryEntity;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author bijiahao
 * @date : 2017/12/18.
 * @description 定时任务-定时上架 执行的具体业务
 *
 */
public class TimelyShelvesQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(TimelyShelvesQuartzJob.class);

    private TimedTaskServiceImpl timedTaskService;
    private MyAsyncOpsMgrServiceImpl myAsyncOpsMgrService;

    public TimelyShelvesQuartzJob() {
        this.timedTaskService = MyAppContextUtil.getBean("timedTaskServiceImpl", TimedTaskServiceImpl.class);
        this.myAsyncOpsMgrService = MyAppContextUtil.getBean("myAsyncOpsMgrServiceImpl", MyAsyncOpsMgrServiceImpl.class);
        Assert.notNull(timedTaskService, "timedTaskServiceImpl 没有注入成功");
        Assert.notNull(myAsyncOpsMgrService, "myAsyncOpsMgrServiceImpl 没有注入成功");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        Assert.notNull(jobDetail, "JobDetail-任务信息没有设置");
        JobDataMap dataMap = jobDetail.getJobDataMap();
        Assert.notNull(dataMap, "JobDataMap-任务信息没有设置");
        Integer resourceId = null;
        try {
            resourceId = dataMap.getIntValue("resourceId");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===resourceId 不能为: " + dataMap.getString("resourceId"));
        }
        String resourceType = dataMap.getString("resourceType");
        Integer resourceVersion = dataMap.getInt("resourceVersion");
        TimedTaskInfoEntity currentTimeTask = timedTaskService.getTimedTaskProvider().queryTimedTaskForTimelyShelves(resourceType, resourceId, resourceVersion);
        if (null == currentTimeTask || currentTimeTask.getStatus() == ResourceStatusEnums.ON_LINE.getStatus()) {
            //如果没有对应定时任务，说明该任务已被取消，或者任务已执行 直接返回
            return;
        }
        //处理定时任务具体业务逻辑
        handleJob(currentTimeTask);
    }

    /**
     * 处理具体业务逻辑
     */
    protected void handleJob(TimedTaskInfoEntity entity) {
        log.info(String.format("====定时上架任务,resourceType: %s,resourceId: %s,resourceVersion: %s", entity.getResourceType(), entity.getResourceId(), entity.getResourceVersion()));
        boolean isOk = timedTaskService.execPutShelvesAndUpdateStatus(entity);
        if (isOk) {
            //需要执行的异步操作 统一处理
            Integer auditorId = getRealAuditorId(entity.getResourceId(), entity.getResourceVersion(), entity.getResourceType());
            myAsyncOpsMgrService.handleCommonAsyncOps(ResourceBaseModel.getResourceBaseModel(entity.getResourceType(), entity.getResourceId(), entity.getResourceVersion()), auditorId);
        }
    }

    private Integer getRealAuditorId(Integer resourceId, Integer resourceVersion, String resourceType) {
        List<AuditTaskInfoHistoryEntity> auditList = AuditUtil.queryAuditHistory(resourceId, resourceVersion, resourceType);
        if (CollectionUtils.isEmpty(auditList)) {
            return null;
        }
        return auditList.get(0).getCurrentOperator();
    }
}
